import 'package:connectivity_plus/connectivity_plus.dart';

/// 网络类型枚举
enum NetworkType {
  mobile,    // 移动数据
  wifi,      // WiFi
  bluetooth, // 蓝牙网络
  ethernet,  // 以太网
  vpn,       // VPN
  other,     // 其他网络类型
  none       // 无网络连接
}

/// 网络信息工具类
class NetworkInfo {
  final Connectivity _connectivity = Connectivity();

  /// 检查当前网络连接状态
  Future<bool> isConnected() async {
    final result = await _connectivity.checkConnectivity();
    return result != ConnectivityResult.none;
  }

  /// 获取当前网络类型
  Future<NetworkType> getNetworkType() async {
    final result = await _connectivity.checkConnectivity();
    
    switch (result) {
      case ConnectivityResult.mobile:
        return NetworkType.mobile;
      case ConnectivityResult.wifi:
        return NetworkType.wifi;
      case ConnectivityResult.bluetooth:
        return NetworkType.bluetooth;
      case ConnectivityResult.ethernet:
        return NetworkType.ethernet;
      case ConnectivityResult.vpn:
        return NetworkType.vpn;
      case ConnectivityResult.other:
        return NetworkType.other;
      case ConnectivityResult.none:
      default:
        return NetworkType.none;
    }
  }

  /// 监听网络连接状态变化
  Stream<bool> get connectionChangeStream {
    return _connectivity.onConnectivityChanged.map((connectivityResult) {
      return connectivityResult != ConnectivityResult.none;
    });
  }

  /// 监听网络类型变化
  Stream<NetworkType> get networkTypeChangeStream {
    return _connectivity.onConnectivityChanged.map((connectivityResult) {
      switch (connectivityResult) {
        case ConnectivityResult.mobile:
          return NetworkType.mobile;
        case ConnectivityResult.wifi:
          return NetworkType.wifi;
        case ConnectivityResult.bluetooth:
          return NetworkType.bluetooth;
        case ConnectivityResult.ethernet:
          return NetworkType.ethernet;
        case ConnectivityResult.vpn:
          return NetworkType.vpn;
        case ConnectivityResult.other:
          return NetworkType.other;
        case ConnectivityResult.none:
        default:
          return NetworkType.none;
      }
    });
  }

  /// 检查是否是WiFi连接
  Future<bool> isWifiConnected() async {
    return await getNetworkType() == NetworkType.wifi;
  }

  /// 检查是否是移动数据连接
  Future<bool> isMobileDataConnected() async {
    return await getNetworkType() == NetworkType.mobile;
  }
}
